import Dialog from '../miniprogram_npm/@vant/weapp/dialog/dialog';

export interface Response<T> {
  code: number;
  message: string;
  data: T extends undefined ? undefined : T;
}

interface RequestConfig {
  url: string;
  data?: any;
  header?: WechatMiniprogram.IAnyObject;
  method?: 'GET' | 'POST';
  timeout?: number;
  dataType?: 'json' | '其他';
  customeError?: boolean;
}

function request<T>(config: RequestConfig) {
  const app = getApp<IAppOption>();

  wx.showLoading({
    title: '加载中',
    mask: true
  });

  return new Promise<Response<T>>((resolve, reject) => {
    wx.request<Response<T>>({
      ...config,
      url: app.globalData.baseUrl + config.url,
      header: {
        ...config.header,
        role: 'client' // 顾客角色
      },
      success(res) {
        resolve(res.data);
      },
      fail(err) {
        reject(err);
      }
    });
  }).then((res) => {
    if (res.code !== 200 && !config.customeError) {
      Dialog.alert({
        title: '请求失败',
        message: res.message
      });
    }
    return res;
  }, (err) => {
    wx.showToast({
      icon: 'error',
      title: err.errMsg
    });
    throw new Error(err.errMsg);
  }).finally(() => {
    wx.hideLoading();
  });
}

export default request;
